package com.ahuiapp.ahuibang;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ahuiapp.ahuibang.engine.HUIEngine;
import com.ahuiapp.ahuibang.util.CustomDialog;
import com.ahuiapp.ahuibang.util.Util;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity implements OnItemClickListener, OnClickListener {
	private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;

	public ProgressDialog pBar;

	private ListView mListView;
	private ImageButton sendButton;
	private ImageButton voiceButton;
	private EditText editMsgView;

	private ArrayList<SiriListItem> list;
	private String DownFileUrl = "";
	private String OldVersion = "";
	private String NewVersion = "";

	ProgressDialog mProgressDialog;
	RelativeLayout mContainer,mEditBar;//,mVoiceBar;
	Context mContext;
	HUIEngine mAHUIEngine;
	ProgressDialog mPgd;
	Dialog mDialog;
	MsgViewAdapter mAdapter;
	boolean isTextMode = true;
	boolean iscanupdate = false;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		if(Util.CheckNetwork(this)){
			isnetwork();
		}else{
			showDialog(1);
		}

	}

	public void isnetwork(){
		mPgd = new ProgressDialog(MainActivity.this);
		mPgd.setMessage("正在加载界面组织数据，请稍等……");
		mPgd.setIndeterminate(false);
		mPgd.setCancelable(false);
		mPgd.show();
		Thread waitM = new Thread(new Runnable(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try{Thread.sleep(5000);}catch(Exception e){}
				mPgd.dismiss();
			}
		});
		waitM.start();
		init();
	}

	private void init() {
		// TODO Auto-generated method stub
		mAHUIEngine = new HUIEngine(this);

		list = new ArrayList<SiriListItem>();
		mAdapter = new MsgViewAdapter(this, list);

		mListView = (ListView) findViewById(R.id.list);
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(this);
		mListView.setFastScrollEnabled(true);
		registerForContextMenu(mListView);

		mContainer=(RelativeLayout)findViewById(R.id.container);
		mEditBar=(RelativeLayout)findViewById(R.id.edit_bottombar);
		mEditBar.setVisibility(View.VISIBLE);
		sendButton= (ImageButton)findViewById(R.id.btn_msg_send);
		sendButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String msgText =editMsgView.getText().toString();
				if (msgText.length()>0) {
					MessageHandle(msgText);	
					editMsgView.setText("");
					editMsgView.clearFocus();

					InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
					imm.hideSoftInputFromWindow(editMsgView.getWindowToken(), 0);
				}else{
					Toast.makeText(MainActivity.this, "发送内容不能为空！", Toast.LENGTH_SHORT).show();
				}
			}
		});

		editMsgView= (EditText)findViewById(R.id.MessageText);	
		editMsgView.clearFocus();
		voiceButton = (ImageButton)findViewById(R.id.btn_msg_voice);
		voiceButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startVoiceRecognitionActivity();
			}
		});
	
		speak("阿辉提示：初始化已完成欢迎使用。", true);
	}
	
	private void startVoiceRecognitionActivity() {
		// TODO Auto-generated method stub
		try{ 
			//通过Intent传递语音识别的模式,开启语音 
			Intent intent = new Intent 
			(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); 
			//语言模式和自由形式的语音识别 
			intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent. 
					LANGUAGE_MODEL_FREE_FORM); 
			//提示语音开始 
			intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"开始语音"); 
			//开始执行我们的Intent、语音识别 
			startActivityForResult(intent,VOICE_RECOGNITION_REQUEST_CODE); 
		}catch (ActivityNotFoundException e){ 
			//找不到语音设备装置 
			Toast.makeText(MainActivity.this,"没有找到相关设备",Toast.LENGTH_LONG).show(); 
		} 
	}
	
	/* 处理语音识别结果
	 * 重写了onActivityResult方法
	 *  */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data){

		if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK){
			// 取得语音的字符 
			ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); 
			//设置视图更新 
			String resultsString = ""; 
			final CharSequence[] items = results.toArray(new CharSequence[results.size()]);
//			for (int i = 0; i < results.size(); i++){ 
//				resultsString += results.get(i); 
//			} 
			
			AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
			builder.setTitle("你说了些什么？").setItems(items, 
				new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					String voicers = items[id].toString();
					if (voicers.length()>0) {
						MessageHandle(voicers);	
					}else{
						Toast.makeText(MainActivity.this, "你什么都没有说！", Toast.LENGTH_SHORT).show();
					}
				}
			});
			AlertDialog alert = builder.create();
			alert.show();
			//Toast.makeText(MainActivity.this,resultsString,Toast.LENGTH_LONG).show(); 
			super.onActivityResult(requestCode, resultCode, data); 
		}
	}


	/**
	 * 动作：
	 * 2011：初始化完成
	 * 2012：返回处理的数据
	 * 2013：返回未处理的数据
	 * 2014：关闭mPgd提示框
	 * 2015：弹出一个mPgd提示框
	 */
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 2011:			 
				speak("初始化完成 欢迎使用", true);
				break;
			case 2012:
				String spkMsg = (String)msg.obj;
				if (spkMsg.length()>0) {
					spkMsg = spkMsg.replaceAll("云", "辉云");
					spkMsg = spkMsg.replaceAll("虫洞官网", "阿辉小站");
					spkMsg = spkMsg.replaceAll("uzoo.cn", "iyouwe.tk");
				}
				speak(spkMsg, true);
				break;
			case 2013:
				speak((String) msg.obj, true);
				break;
			case 2014:
				mPgd.dismiss();
				break;
			case 2015:
				IsDownLoadFile((Boolean)msg.obj);
				break;
			}
			super.handleMessage(msg);
		}
	};

	/**数据句柄：作用于将消息添加到LIST中去，
	 * 			同时还要判断出是否为网络消息还是人工发送的消息
	 * @param msgText 内容
	 */
	private void MessageHandle(String msgText) {
		// TODO Auto-generated method stub
		addToList(msgText, false);
		msgText = msgText.replaceAll("。$", "");
		mAHUIEngine.handlerAnswer(msgText, handler);
	}

	public void speak(String msg, boolean isfromNet) {
		addToList(msg, isfromNet);
	}
	
	private void addToList(String msgText, boolean b) {
		// TODO Auto-generated method stub
		list.add(new SiriListItem(msgText, b));
		mAdapter.notifyDataSetChanged();
		mListView.setSelection(list.size() - 1);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		SiriListItem item = list.get(arg2);
		if (item.isfromNet) {
			new CustomDialog(MainActivity.this,
					CustomDialog.DIALOG_DETAILS,"消息来自网络",item.message).show();
		}else{
			new CustomDialog(MainActivity.this,
					CustomDialog.DIALOG_DETAILS,"你输入的问题",item.message).show();
		}
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub

	}

	public class SiriListItem {
		String message;
		boolean isfromNet;

		public SiriListItem(String msg, boolean b) {
			message = msg;
			isfromNet = b;
		}
	}

	public boolean onCreateOptionsMenu(Menu menu){
		menu.add(0,0,0,R.string.btnAbout);
		menu.add(0,1,0,R.string.btnreturn);
		menu.add(0,2,0,R.string.btnupd);  
		menu.add(0,3,0,R.string.btnhelp); 

		return super.onCreateOptionsMenu(menu);
	}
	public boolean onOptionsItemSelected(MenuItem item){
		super.onOptionsItemSelected(item);
		switch(item.getItemId()){
		case 0:
			about();
			break;
		case 1:
			finish();
			break;
		case 2:
			update();
			break;
		case 3:
			help();
			break;
		}
		
		return true;
	}

	private void help() {
		// TODO Auto-generated method stub
		new CustomDialog(MainActivity.this,
				CustomDialog.DIALOG_DETAILS,"消息来自网络","暂无帮助信息。").show();
	}

	private void update() {
		mPgd = new ProgressDialog(this);
		mPgd.setMessage("正在检查版本信息，请稍等…… ^_^");
		mPgd.setCancelable(true);
		mPgd.show();
		Thread waitM = new Thread(new Runnable(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				iscanupdate = false;
				try{
					iscanupdate = getServerVer();
				}catch(Exception e){}
				handler.sendEmptyMessage(2014);//关闭mPgd
				//打开 一个对话框，告知否可以下载更新应用。
				Message message = new Message();
				message.what = 2015;
				message.obj = iscanupdate;
				handler.sendMessage(message);	
			}
		});
		waitM.start();
	}
	
	private void about() {
		// TODO Auto-generated method stub
		new AlertDialog.Builder(this)
		.setTitle(R.string.app_name)
		.setMessage(R.string.labelTipText)
		.setPositiveButton(R.string.btnOk, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			}
		}).show();
	}
//-------------------------------------------------//
    public double getOldVerName() {
    	double verName = 0.0;
        String pName = "com.ahuiapp.ahuibang";
        try {
            PackageInfo pinfo = getPackageManager().getPackageInfo(pName, PackageManager.GET_CONFIGURATIONS);
            verName = Double.valueOf(pinfo.versionName);
            OldVersion = String.valueOf(verName);
        } catch (NameNotFoundException e) {}
        return verName;
    }
    
    private boolean getServerVer() {
    	double newVerName = 0;
    	boolean isUpdate = false;
        try {
            String verjson = mAHUIEngine.getAPPVer();
            JSONArray array = new JSONArray(verjson);
            if (array.length() > 0) {
                JSONObject obj = array.getJSONObject(0);
                try {
                    newVerName = Double.valueOf(obj.getString("verName"));
                    if(newVerName>getOldVerName()){
                    	isUpdate = true;
                    	DownFileUrl = obj.getString("apkname");
                    	NewVersion = String.valueOf(newVerName);
                    }else{
                    	isUpdate = false;
                    }
                } catch (Exception e) {
                    newVerName = 0;
                    return isUpdate;
                }
            }
        } catch (Exception e) {
            return isUpdate;
        }
        return isUpdate;
    }

	private void IsDownLoadFile(Boolean isok) {
		// TODO Auto-generated method stub
		//mPgd.dismiss();
		if(isok){
			new AlertDialog.Builder(MainActivity.this)
			.setIcon(android.R.drawable.stat_sys_upload)
			.setTitle(R.string.app_name)
			.setMessage("有新版本可做更新操作，当前版本为“"+OldVersion+"”,最新版本为“"+NewVersion+"”，是否下载更新？")
			.setPositiveButton(R.string.btnOk, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					Intent intent = new Intent();        
					intent.setAction("android.intent.action.VIEW");    
					Uri content_url = Uri.parse("http://www.iyouwe.tk/fileup/"+DownFileUrl);
					intent.setData(content_url);  
					startActivity(intent);
				}
			}).setNegativeButton(R.string.btnUnOk, new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					arg0.cancel();
				}
			}).show();
		}else{
			new CustomDialog(MainActivity.this,
					CustomDialog.DIALOG_DETAILS,"消息来自网络","当前版本为最新，不用更新,请返回。").show();
		}
	}

//---------------------------------------------------------//
}